package com.lagou.zookeeper;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ZookeeperUtil {

    private String host;
    private Integer port;
    private ZkClient zkClient;


    public ZookeeperUtil(String host, Integer port){
        this.host = host;
        this.port = port;
        zkClient = new ZkClient(host + ":" + port);
    }


    public List<String> readServerList(){
        String parentPath = "/server";
        List<String> children = zkClient.getChildren(parentPath);
        List<String> serverList = new ArrayList<>();
        for (String subPath : children){
            serverList.add(subPath);
        }
        System.out.println(serverList);
        return serverList;
    }


    public void watchServerList(DataChange dataChange){
        zkClient.subscribeChildChanges("/server", new IZkChildListener() {
            @Override
            public void handleChildChange(String s, List<String> list) throws Exception {
                dataChange.dataChange(s,list);
            }
        });
    }

    public void writeResponseTimeMap(Map<String,Long> responseTimeMap){
        String metricsPath = "/metrics";
        if (!zkClient.exists(metricsPath)){
            zkClient.createPersistent(metricsPath);
        }
        if (responseTimeMap != null && responseTimeMap.size() > 0){
            for (String key : responseTimeMap.keySet()){
                String path = "/metrics/" + key;
                if (!zkClient.exists(path)){
                    zkClient.createPersistent(path);
                }
                Long responseTime = responseTimeMap.get(key);
                zkClient.writeData(path,responseTime);
                System.out.println("上报服务器响应时间：" + key + "==>" + responseTime);
            }
        }
    }

    public Map<String,Long> readResponseTimeMap(){
        String metricsPath = "/metrics";
        if (!zkClient.exists(metricsPath)){
            zkClient.createPersistent(metricsPath);
        }
        Map responseTimeMap = new HashMap();
        List<String> children = zkClient.getChildren(metricsPath);
        for (String path : children){
            Long responseTime = zkClient.readData(metricsPath + "/" + path);
            responseTimeMap.put(path,responseTime);
        }

        return responseTimeMap;
    }

}
